﻿using PSI.Helper;
using PSI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PSI.Services {
    public class LogService : PSIBaseService {
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="log"></param>
        private void Log(Log log) {
            var p = CreateDbParameters();
            p.AddWithValue("userId", log.UserId);
            p.AddWithValue("loginName", log.LoginName);
            p.AddWithValue("userName", log.UserName);
            p.AddWithValue("logIP", log.IP);
            p.AddWithValue("logContent", log.LogContent);

            var sql = @"insert into psi_log(user_id, login_name, user_name, log_ip, log_content)
                values (@userId, @loginName, @userName, @logIP, @logContent)";

            Execute(sql, p);
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="info">日志内容</param>
        public void Log(string info) {
            Log(new Log { LogContent = info });
        }

        public int GetLogTotalCount() {
            var sql = "select count(*) from psi_log";
            var p = CreateDbParameters();

            return QueryCount(sql, p);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page">从1开始</param>
        /// <param name="start">从0开始</param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public List<Log> GetLog(int page, int start, int limit) {
            if (start == 0) {
                start = 1;
            }

            var result = new List<Log>();

            var sql = @"
                with psi_log_paged as (
                select login_name, user_name, log_ip, log_content, log_datetime, log_id,
                            row_number() over (order by log_datetime desc) as 'row_num' 
                        from psi_log )

                select * from psi_log_paged where row_num between "
                + start.ToString() + " and " + (start + limit - 1).ToString();

            Query(sql, reader => {
                var log = new Log {
                    LoginName = reader.GetString(0),
                    UserName = reader.GetString(1),
                    IP = reader.GetString(2),
                    LogContent = reader.GetString(3),
                    DT = reader.GetDateTime(4).ToString("yyyy-MM-dd HH:mm:ss"),
                    Id = reader.GetInt32(5)
                };

                result.Add(log);
            });
            return result;
        }
    }
}